package utils;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class Index {
	//number of result of affichage
	private HashMap<String, HashMap<String, PosInfo>> idx;
	
	private int nbDoc=-1;
	
	public Index()
	{
		this.idx=new HashMap<String, HashMap<String, PosInfo>>();
	}
	public boolean hasEntry(String word)
	{
		return this.idx.containsKey(word);
	}
	public void setNbDoc(int b)
	{
		this.nbDoc=b;
	}
	public int getNbDoc()
	{
			return this.nbDoc;
	}
	
	public void insert(String word, String filename,  PosInfo ps)
	{
		if(this.idx.containsKey(word))
		{
			this.idx.get(word).put(filename, ps);
		}
		else
		{
			HashMap<String, PosInfo> hm=new HashMap<String, PosInfo>();
			hm.put(filename, ps);
			this.idx.put(word, hm);
		}
	}
	public void insert(String word, String filename, int pos)
	{	
		//if contains the term
		if(this.idx.containsKey(word))
		{	
			//if this term already exists in the file
			if(this.idx.get(word).containsKey(filename))
			{
				this.idx.get(word).get(filename).incrementSize();
			}
			//if this term first occurs in the file
			else
			{
				PosInfo pi=new PosInfo();
				pi.incrementSize();
				//posList.add(pos);
				this.idx.get(word).put(filename, pi);
			}
		}
		//if index not contains the term
		else
		{
			HashMap<String, PosInfo> hp=new HashMap<String, PosInfo>();
			PosInfo pi=new PosInfo();
			pi.incrementSize();
			//posList.add(pos);
			hp.put(filename, pi);
			this.idx.put(word, hp);
		}
	}
	
	public HashMap<String, PosInfo> get(String word)
	{
		return idx.get(word);
	}
	
	
	public void printToFile(String filename, ArrayList<String> files) throws IOException
	{
		FileOutputStream fos = new FileOutputStream(filename);  
		OutputStreamWriter os = new OutputStreamWriter(fos, "UTF-8");  
		BufferedWriter bWriter=new BufferedWriter(os);
		//BufferedWriter os = new BufferedWriter(new FileWriter(new File(filename)));
		Set<String> wordSet = idx.keySet();
		Iterator<String> itr = wordSet.iterator();
		while(itr.hasNext())
		{
			String word = itr.next();
			bWriter.write(word+"\n");
			HashMap<String,PosInfo> map = idx.get(word);
			for(String name : map.keySet())
			{
				int id=files.indexOf(name);
				bWriter.write(id+":"+map.get(name).toString());
				bWriter.write("\t");
			}
			//os.write("\t"+map.toString());
			bWriter.write("\n\n");
		}
		bWriter.close();
	}
}
